﻿using AutoMapper;
using Chat.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xiao.Application.Dto;
using Xiao.Code.Entities.User;
using Xiao.Code.Entities.Users;
using Xiao.EntityFrameworkCore.Core;
using Xiao.EntityFrameworkCore.Repository;
using Xiao.EntityFrameworkCore.Repository.User;

namespace Xiao.Application.Services.User
{
    public interface IFriendsService
    {
        Task<List<FriendsDto>> GetFriendsList(Guid id);
        Task<List<FriendsDto>> GetFroemdIds(Guid userId);
    }
    public class FriendsService : BaseService<Friends>, IFriendsService
    {
        private readonly IMapper _mapper;
        private readonly IConsumerRepository _consumerRepository;
        public FriendsService
            (IMapper mapper,
            IConsumerRepository consumerRepository,
            IUnitOfWork<MasterDbContext> unitOfWork,
            IMasterDbRepositoryBase<Friends> currentRepository)
            : base(unitOfWork, currentRepository)
        {
            _mapper = mapper;
            _consumerRepository = consumerRepository;
        }

        public async Task<List<FriendsDto>> GetFriendsList(Guid id)
        {
            var data=await currentRepository
                .FindAll(a=>a.ConsumerId==id)
                .Include(a=>a.Friend)
                .ToListAsync();
            var ids=data.Select(a=>a.ConsumerId);
            var consumers= _mapper.Map<List<ConsumerDto>>(_consumerRepository.FindAll(a=>ids.Contains(a.Id)).ToList());
            var dataDto= _mapper.Map<List<FriendsDto>>(data);
            foreach (var d in dataDto)
            {
                var consumer = consumers.Where(a => a.Id == d.ConsumerId).FirstOrDefault();
                if (consumer != null)
                {
                    d.Consumer = consumer;
                }
            }
            return dataDto;
        }

        public async Task<List<FriendsDto>> GetFroemdIds(Guid userId)
        {
            var data= await currentRepository.FindAll(a=>a.ConsumerId == userId)
                .Include(a=>a.Friend)
                .ToListAsync();
            return _mapper.Map<List<FriendsDto>>(data);
        }
    }
}
